package org.lztvn.elearning.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.lztvn.elearning.entities.Topic;

public class TopicDaoImpl implements ITopicDao{
	@PersistenceContext
	private EntityManager em;
	@Override
	public Long addTopic(Topic t) {
		em.persist(t);
		return t.getIdTopic();
	}

	@Override
	public void deleteTopic(Long idTopics) {
		Topic t = em.find(Topic.class, idTopics);
		em.remove(t);
	}

	@Override
	public void modifierTopic(Topic t) {
		em.merge(t);
	}

	@Override
	public List<Topic> listTopic(int position, int nb_topic) {
		Query req = em.createQuery("select t from Topic t");
		req.setFirstResult(position);
		req.setMaxResults(nb_topic);
		return req.getResultList();
	}

	@Override
	public List<Topic> listTopicByUserId(Long idUser, int position, int nb_topic) {
		Query req = em.createQuery("select t from Topic t where idUser = :x order by t.dateMsg asc");
		req.setParameter("x",idUser);
		req.setFirstResult(position);
		req.setMaxResults(nb_topic);
		return req.getResultList();
	}

	@Override
	public Topic getTopic(Long idTopic) {
		return em.find(Topic.class, idTopic);
	}

	@Override
	public Long getNbTopicByUserId(Long idUser) {
		Query req = em.createQuery("select count(t) from Topic t where idUser = :x");
		req.setParameter("x",idUser);
		return (Long) req.getResultList().get(0);
	}

	@Override
	public Long getNbTopic() {
		Query req = em.createQuery("select count(t) from Topic t");
		return (Long) req.getResultList().get(0);
	}

}
